<?php

/**
 * 将html转为md
 * 按文件夹
 */
$LIB = dirname(__FILE__);

require_once($LIB. "/vendor/autoload.php");
use League\HTMLToMarkdown\HtmlConverter;
use League\HTMLToMarkdown\Converter\TableConverter;
use League\HTMLToMarkdown\Converter\PreformattedConverter;
use League\HTMLToMarkdown\Converter\CodeConverter;

$options = getopt("s:d:");
$src = $options['s'] ?? '';
$dst = $options['d'] ?? $src . "/md";
if (empty($src) || empty($dst)) {
    exit("usage: php $argv[0] -s src_dir -d dst_dir");
}

if (!is_dir($src)) {
    exit($src . " 不存在");
}

if (!is_dir($dst)) {
    @mkdir($dst, 0755, true);
}

$converter = new HtmlConverter(array('strip_tags' => true));
$converter->getEnvironment()->addConverter(new TableConverter());
$converter->getEnvironment()->addConverter(new PreformattedConverter());
$converter->getEnvironment()->addConverter(new CodeConverter());
// $converter->getConfig()->setOption('strip_tags', true);

$files = glob("{$src}/*.html");
// print_r($files);
foreach($files as $file) {
    // echo $file;
    $content = file_get_contents($file);

    // convert to md
    // 判断本身是不是markdown
    if (!isMd($content)) {
        // 去除css、script
        $content = preg_replace('/<style(.*?)<\/style>/s', '', $content);
        $content = preg_replace('/<script(.*?)<\/script>/s', '', $content);

        // html_entity_decode
        $content = html_entity_decode($content);

        $markdown_show = $converter->convert($content);

        // $markdown_show = str_replace('\#', '#', $markdown_show);
    } else {
        $markdown_show = $content;
    }

    // 去除pre里的标签，可能会误伤，依情况开启
    $markdown_show = strip_tags($markdown_show, "<xml>");

    // output
    file_put_contents($dst . "/". basename($file, ".html") . ".md", $markdown_show);
}

function isMd($content){
    if (false !== stripos($content, "<p>")) {
        return false;
    }

    if (false !== stripos($content, "<a>")) {
        return false;
    }

    if (false !== stripos($content, "<div>")) {
        return false;
    }

    if (false !== stripos($content, "<span>")) {
        return false;
    }

    return true;
}